<template>
	<view class="order-pages" :style="{ background: pageColor }">
		<scroll-view scroll-y class="scroll" :style="{ height: `calc(100vh - ${headerHeight}px)` }"
			:scroll-top="scrollTop" :scroll-into-view="scrollIntoView" scroll-with-animation @scroll="onScroll">
			<view class="warp">
				<view class="content-box">
					<view class="content-box-title">我的资料</view>
					<view class="flex">
						<!-- <view class="flex-left">
							<view class="photo-img">
								<uploadNew @upload="imgUpload" :imagelist="form.text_img" style="height: 150rpx;"
									filetype="picture" imgtype="text_img" text="上传图片" :imgsize="1">
								</uploadNew>
							</view>
						</view> -->
						<view class="flex-right">
							
						</view>
					</view>
					<view class="form-item disflex">
						<view class="form-item-title pl40">姓名：</view>
						<input class="uni-input" type="text" v-model.trim="form.coach_name" />
					</view>
					<view class="form-item disflex">
						<view class="form-item-title pl40">性别：</view>
						<picker @change="pickerChange($event, 'sex')" range-key="name" :range="sexList">
							<view>
								<text v-if="!form.sex" class="placeholder-style">请选择性别</text>
								<text v-else>{{ form.sexName }}</text>
							</view>
						</picker>
					</view>
					<view class="form-item disflex">
						<view class="form-item-title pl40">出生日期：</view>
						<view class="item-input text flex-1">
							<picker @change="pickerChange($event, 'birthday')" mode="date" :value="form.birthday">
								<view class="flex-between">
									{{ form.birthday || '请选择' }}
								</view>
							</picker>
						</view>
					</view>
					<view class="form-item disflex">
						<view class="form-item-title pl40">手机号码：</view>
						<input class="uni-input" type="number" v-model.trim="form.mobile" maxlength="11" />
					</view>
					<view class="form-item disflex">
						<view class="form-item-title pl40">身份证号码：</view>
						<input class="uni-input" type="idcard" v-model="form.id_code" maxlength="18" />
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import {
	mapState,
	mapActions,
	mapMutations
} from "vuex"
import $util from "@/utils/index.js"
export default {
	components: {

	},
	data() {
		return {
			headerHeight: 0,
			pendingUpload: false, // 添加这个标记
			form: {
				text_img: [], // 修改为数组
				coach_name: '', // 姓名
				sex: '', // 性别
				birthday: '', // 出生日期
				mobile: '', // 手机号码
				id_code: '', // 身份证
				city: '', // 工作意向地
				sexName: '',
				text: '', // 自我介绍
				id_img_positive: '', // 身份证正面
				id_img_negative: '', // 身份证反面
				id_card: [], // 身份证正面
				id_card_fan: [], // 身份证正面
				license: [], // 技能证书展示
				self_img: [], // 技能照片展示
				self_video: [], // 技能视频展示
			},
			cityList: [],
			cityIndex: -1,
			sexList: [{
				name: '男',
				id: 1
			},
			{
				name: '女',
				id: 2
			}
			],
			rule: [
			{
				name: "id_card",
				checkType: "isNotNull",
				errorMsg: "请上传身份证正面照片",
				regType: 1
			},
			{
				name: "id_card_fan",
				checkType: "isNotNull",
				errorMsg: "请上传身份证反面照片",
				regType: 1
			},
			{
				name: "license",
				checkType: "isNotNull",
				errorMsg: "请上传技能证书照片",
				regType: 1
			},
			{
				name: "self_img",
				checkType: "isNotNull",
				errorMsg: "请上传技能展示照片",
				regType: 1
			},
			{
				name: "self_video",
				checkType: "isNotNull",
				errorMsg: "请上传技能是视频",
				regType: 1
			}
			],
			type: ''
		}
	},
	computed: mapState({
		configInfo: state => state.config.configInfo,
	}),

	// 添加 watch 监听
	watch: {
		// 监听隐私授权状态变化
		'$store.state.user.resolvePrivacy': {
			handler(newVal) {
				console.log('隐私状态变化:', newVal)
				// 只有在用户同意且有待处理的上传时才执行
				if (newVal && newVal.event === 'agree' && this.pendingUpload) {
					this.pendingUpload = false
					console.log('隐私同意，开始上传图片')
					// 延迟执行确保隐私状态已更新
					setTimeout(() => {
						this.doChooseImage()
					}, 500)
				}
			},
			deep: true
		}
	},
	async onLoad(options) {
		this.$util.setNavigationBarColor({
			bg: this.primaryColor
		})
		this.getBaseInfo()
		console.log(options, 'options')
		this.type = options.type ? options.type : ''
		console.log(this.configInfo, 'configInfo')
		console.log(this.$store.state.user.userInfo, 'sssss')
		this.getDetail()
		// this.form = ''
	},
	methods: {
		onScroll(event) { },
		imgUpload(e) {
			let {
				imagelist,
				imgtype
			} = e;
			this.form[imgtype] = imagelist;
		},
		pickerChange(e, key) {
			let ind = e.target.value
			if (key === 'birthday') {
				let unix = this.$util.DateToUnix(ind)
				if (unix > new Date(Math.ceil(new Date().getTime())) / 1000) {
					this.$util.showToast({
						title: `不能选择未来时间哦`
					})
					return
				}
				this.form[key] = ind
				return
			}
			if (key === 'sex') {
				console.log(e.target.value, 'e.target.value')
				this.form.sexName = this.sexList[e.target.value].name
				this.form.sex = this.sexList[e.target.value].id
				return
			}
			if (key === 'city') {
				console.log(e.target.value, 'jinlaile')
				this.form.city = this.cityList[e.target.value].title
				// this.form.cityText = this.cityList[e.target.value].id
				this.form.city_id = this.cityList[e.target.value].id
				
				return
			}
			
			if (ind == -1) return

			this[`${key}Index`] = ind
			let {
				id
			} = this[`${key}List`][ind]
			if (key === 'industry') {
				this.form[`${key}_type`] = id
			} else if (key === 'personality') {
				this.form[`${key}_icon`] = id
			} else {
				this.form[`${key}_id`] = id
			}
			if (key === 'city') {
				console.log('jinlaile')
				// this.getStationIconSelect()
			}
			
		},
		async getBaseInfo() {
			let {
				career = false
			} = this.configInfo.plugAuth
			if (career) {
				this.typeList = await this.$api.technician.coachTypeSelect()
			}

			let {
				admin_id = 0
			} = this.form
			let {
				agent_update_city
			} = this.configInfo
			if (!admin_id || agent_update_city) {
				let {
					lat = 0, lng = 0
				} = this.location
				let city = await this.$api.base.getCity({
					lat,
					lng
				})
				this.cityList = city
			}
		},
		bindTextAreaBlur(e) {
			console.log(e.detail.value)
			this.form.text = e.detail.value
		},
		//表单验证
		validate(param) {
			let validate = new this.$util.Validate();
			this.rule.map(item => {
				let {
					name,
				} = item
				validate.add(param[name], item);
			})
			let message = validate.start();
			return message;
		},
		async workerClick() {
			let param = this.$util.deepCopy(this.form)
			let msg = this.validate(param);
			if (msg) {
				this.$util.showToast({
					title: msg
				});
				// return;
			}
			const id_card = [...this.form.id_card, ...this.form.id_card_fan]
			param.id_card = id_card.map(item => item.path)
			// param.work_img = this.form.text_img.map(item => item.path)
			param.work_img = this.form.text_img[0] ? this.form.text_img[0].path : ''
			param.license = this.form.license.map(item => item.path)
			param.self_img = this.form.self_img.map(item => item.path)
			param.self_video = this.form.self_video[0] ? this.form.self_video[0].path : ''
			param.work_time = this.form.birthday
			delete param.id_card_fan
			delete param.birthday
			delete param.city
			delete param.id_img_negative
			delete param.id_img_positive
			delete param.text_img
			delete param.sexName
			
			console.log(param, 'param')
			// return false
			try {
				await this.$api.technician.coachApply(param)
				this.$util.hideAll()
				let url = '/pages/mine'				
				setTimeout(() => {					
					this.$util.goUrl({
						url,
						openType: `reLaunch`
					})
				}, 500)
			} catch (e) {
				setTimeout(() => {
					this.lockTap = false
					this.$util.hideAll()
					let url = '/pages/mine'
					this.$util.goUrl({
						url,
						openType: `reLaunch`
					})
				}, 500)
			}
		},
		upload() {
			let privacyCheck = this.$refs.user_privacy.check()
			console.log(privacyCheck, 'privacyCheck')
			if (!privacyCheck) {
				// 设置等待上传标记
				this.pendingUpload = true
				this.$refs.user_privacy.open()
				return
			}
			// 隐私检查通过，直接上传
			this.doChooseImage()
		},

		// 删除 waitForPrivacyAuth 方法，保留 doChooseImage 方法
		doChooseImage() {
			uni.chooseImage({
				count: 1,
				sizeType: ["compressed"],
				sourceType: ["album", "camera"],
				success: async (res) => {
					console.log(res);
					this.$util.showLoading({
						title: "上传中"
					});

					try {
						// 上传图片到服务器
						let { attachment_path: path } = await this.$api.base.uploadFile({
							filePath: res.tempFilePaths[0],
							formData: {
								type: 'picture'
							}
						});

						// 更新表单数据
						if (!this.form.text_img) {
							this.form.text_img = [];
						}
						this.form.text_img = [{ path }];

						this.$util.hideAll();
						this.$util.showToast({
							title: "上传成功"
						});
					} catch (error) {
						console.error('上传失败:', error);
						this.$util.hideAll();
						this.$util.showToast({
							title: "上传失败，请重试"
						});
					}
				},
				fail: (error) => {
					console.error('选择图片失败:', error);
					this.$util.showToast({
						title: "选择图片失败"
					});
				}
			});
		},
		
		// 预览图片
		previewImage() {
			if (this.form.text_img.length > 0) {
				uni.previewImage({
					urls: [this.form.text_img[0].path],
					current: 0
				})
			}
		},
		
		// 删除图片
		deleteImage() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这张照片吗？',
				success: (res) => {
					if (res.confirm) {
						this.form.text_img = []
						this.$util.showToast({
							title: "删除成功"
						})
					}
				}
			})
		},
		userClick(type){
			let url = `/user/pages/protocol`
			if(type === 'user'){
				url = `/user/pages/information`
			} else if(type === 'privacy') {
				url = `/user/pages/protocol`	
			} else if(type === 'worker') {
				url = `/user/pages/information`
			}
			this.$util.goUrl({
				url
			})
		},
		async getDetail() {
			let {
				id
			} = this.options
			let data = await this.$api.service.coachInfo({
				id
			})
			let {
				industrytype
			} = this.configInfo.plugAuth
			if (data.industry_data) {
				if (industrytype == 1) {
					data.industry_data.business_license = 0
					data.industry_data.health_certificate = 0
				}
				if (industrytype == 1 || data.industry_data.type == 1) {
					data.industry_data.age_sex = 0
				}
				if (industrytype == 2 || data.industry_data.type == 2) {
					data.industry_data.age_sex = 1
				}
			}
			data.banner = data.video ? [{
				jump_type: 'video',
				img: data.work_img,
				jump_url: data.video
			}] : [{
				img: data.work_img
			}]
			data.arrBanner = data.banner.concat(data.self_img)
			let have_show_text = data.text.length > 42
			data.have_show_text = have_show_text
			data.showText = !have_show_text
			data.industry_show = 0
			data.certificate_show = 0
			data.star = (data.star * 1).toFixed(1)
			Array.from(['employment_years', 'height', 'weight', 'constellation']).map(item => {
				if (data.industry_data[item]) {
					data.industry_show = 1
				}
			})
			Array.from(['business_license', 'health_certificate', 'massage_certificate', 'id_card',
				'avatar_verification'
			]).map(item => {
				if (data.industry_data[item]) {
					data.certificate_show = 1
				}
			}) 
			let {
				store_id = 0,
					store_name = ''
			} = data
			data.store = store_id && store_name ? [{
				id: store_id,
				title: store_name
			}] : data.store || []
			this.detail = data
			console.log(this.detail, 'this.detail')
		},   
	}
}
</script>


<style lang="scss">
.warp {
	background-color: #fff;
	// border-top-left-radius: 20rpx; 
	// border-top-right-radius: 20rpx; 
	overflow: hidden;

	.content-box {
		width: 750rpx;
		border-radius: 20rpx 20rpx 0 0;
		background-color: #ffffff;
		overflow: hidden;
		margin-top: -20rpx;
		position: relative;

		.content-box-title {
			height: 120rpx;
			line-height: 140rpx;
			padding: 0 50rpx;
			border-bottom: 1rpx solid #D5D5D5;
			font-family: Source Han Sans, Source Han Sans;
			font-weight: 500;
			font-size: 40rpx;
			color: #000000;
		}

		.flex {
			display: flex;
			// border-top: 1rpx solid #D5D5D5;
		}

		.flex-left {
			width: 224rpx;
			// height: 182rpx;
			height: 174rpx;
			border-radius: 0px 0px 0px 0px;
			border-right: 1rpx solid #D5D5D5;
			border-bottom: 1rpx solid #D5D5D5;
		}

		.flex-right {
			// width: 524rpx;
		}

		.photo-img {
			width: 101rpx;
			height: 150rpx;
			margin: 14rpx auto;
			position: relative;
			text-align: center;
			border: 1rpx solid #A3A3A3;
			overflow: hidden;
			.uploaded-image {
				width: 100%;
				height: 120rpx;
				border-radius: 4rpx;
			}
			
			.image-actions {
				display: flex;
				justify-content: space-between;
				margin-top: 4rpx;
				
				.action-btn {
					font-size: 12rpx;
					color: #666;
					padding: 2rpx 4rpx;
					border: 1rpx solid #ddd;
					border-radius: 2rpx;
					text-align: center;
					flex: 1;
					margin: 0 2rpx;
				}
				
				.delete-btn {
					color: #ff4d4f;
					border-color: #ff4d4f;
				}
			}
		}

		.form-item {
			width: 100%;
			border-bottom: 1rpx solid #D5D5D5;
			padding: 22rpx 0;

			.form-item-title {
				font-family: Source Han Sans, Source Han Sans;
				font-weight: 400;
				font-size: 30rpx;
				color: #000000;
			}

			.uni-input {
				// width: ;
				padding: 0 10rpx;
			}

			.textarea {
				width: 625rpx;
				height: 180rpx;
				padding: 20rpx 62rpx;
			}

			.id-card {
				width: 300rpx;
				height: 200rpx;
				// border: 1px solid #A3A3A3;
				display: flex;
				align-items: center;
				justify-content: center;

				.id-card-text {
					font-family: Source Han Sans, Source Han Sans;
					font-weight: 400;
					font-size: 20rpx;
					color: #AEAEAE;
				}
			}

			.skill-box {
				// width: 624rpx;
				width: 710rpx;
				// height: 200rpx;
				border-radius: 0px 0px 0px 0px;
				border: 1rpx solid #A3A3A3;
				display: flex;
				align-items: center;
				// justify-content: center;
				margin: 20rpx auto;
				padding: 10rpx;
				.skill-box-text {
					font-family: Source Han Sans, Source Han Sans;
					font-weight: 400;
					font-size: 20rpx;
					color: #AEAEAE;
				}
			}

			.checkbox-text {
				font-family: Source Han Sans, Source Han Sans;
				font-weight: 400;
				font-size: 24rpx;
				color: #9A9A9A;
			}
		}

		.pl40 {
			padding-left: 40rpx;
		}

		.pl62 {
			padding-left: 62rpx;
		}

		.pr62 {
			padding-right: 62rpx;
		}
		.pl24 {
			padding-left: 24rpx;
		}
		.disflex {
			display: flex;
			align-items: center;
		}

		.btn-box {
			padding: 60rpx 0;
			display: flex;
			align-items: center;
			justify-content: center;

			.order-btn {
				width: 300rpx;
				height: 64rpx;
				background: #6EC2B0;
				border-radius: 32rpx 32rpx 32rpx 32rpx;
				font-family: Source Han Sans, Source Han Sans;
				font-weight: 400;
				font-size: 30rpx;
				color: #FFFFFF;
				text-align: center;
				line-height: 64rpx;
			}
		}
	}
	.round-checkbox{
		width: 70rpx;
	}
}
</style>